/**
 * Created by user on 2015/9/7.
 */


var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var Regions = mongoose.model('masterData_Regions');

exports.creatRegionByCityService = function(input, res,callback) {


    var city= input.name;
    var key= '7VKBZ-GRK3U-XCJVG-4RSWJ-JMEDQ-MBBAX';

    restClient.get(encodeURI('http://apis.map.qq.com/ws/district/v1/search?&keyword='+ city +'&key='+key), function (data, response) {

        if(data) {

            logger.debug(data.toString());


            var obj = JSON.parse(data.toString());
            logger.debug(obj);

            //if(obj.address.split(',')>2){
            //    logger.debug()
            //}

            if(obj.status==0) {

                var cityId = obj.result[0][0].id;

                if(cityId) {
                    restClient.get('http://apis.map.qq.com/ws/district/v1/getchildren?id=' + cityId + '&key=' + key, function (data, response) {

                        var opt = {
                            name: input.name,
                            type: 'city'
                        }
                        //logger.debug(data.toString());

                        var obj = JSON.parse(data.toString());

                        logger.debug(obj.result);
                        logger.debug(input);
                        var cityid = null;

                        async.series([
                            function (callbackInner) {
                                Regions.find(opt).exec(function (err, results) {

                                    if (err) {
                                        return callbackInner(err);
                                    } else {
                                        if (results) {
                                            logger.debug(results[0]);
                                            cityid = results[0]._id;
                                        }
                                        return callbackInner(null, results);
                                    }
                                })
                            },
                            function (callbackInner) {
                                Regions.find({parentId: cityid}).exec(function (err, results) {

                                    if (err) {
                                        return callbackInner(err);
                                    } else {
                                        logger.debug(results.length);
                                        if (results.length > 0) {
                                            var err = {
                                                type: 'warning',
                                                message: '该城市县区已初始化过！'
                                            };
                                            callbackInner(err, null);
                                        } else {

                                            callbackInner(null, results);
                                        }
                                        ;

                                    }
                                    ;
                                })
                            },
                            function (callbackInner) {
                                async.eachSeries(obj.result[0], function (reg, callbackInner) {
                                    //logger.debug(reg);
                                    //logger.debug(reg.fullname);
                                    var temp = new Regions();
                                    temp.parentId = cityid;
                                    temp.cultureCode = 'zh-CN';
                                    temp.type = 'county';
                                    temp.name = reg.fullname;
                                    logger.debug(temp);
                                    temp.save(callbackInner);
                                }, callbackInner);
                            }
                        ], callback);


                    })
                }else{
                    var err = {
                        type: 'warning',
                        message: '城市：'+city +'不存在！'
                    };
                    callback(err);
                }
            }
        }else{
            var err = {
                type: 'warning',
                message: '城市：'+city +'不存在！'
            };
            callback(err);
        }
    });

};


exports.regionsListService = function(req ,callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;


    var opt={};
    if (body.parentId) opt.parentId = body.parentId;

    logger.debug(opt);

    async.series([

        function (callbackInner) {
            Regions.count(opt, function (err, count) {

                if (err) {
                    return callbackInner(err, null);
                } else {
                    logger.debug(count);
                    var temp = {count: count, page: Math.ceil(count/size)};
                    callbackInner(null, temp);
                }
            });
        },
        function (callbackInner) {
            logger.debug(opt);
            Regions.find(opt).skip(index).limit(size)
                .populate('parentId', 'name')
                .sort({parentId: 1})
                .exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {
                        callbackInner(null, results);
                    }
                })
        }
    ], callback);


}